package com.ui;

import com.service.GroupService;
import com.service.StudentService;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Random;

public class RandomStudentDialog {
    private JDialog dialog;
    private JButton selectButton;
    private JLabel resultLabel;
    private List<String> students;
    private GroupService groupService;
    private String currentClass;

    public RandomStudentDialog(StudentService studentService, GroupService groupService, String currentClass) {
        this.groupService = groupService;
        this.currentClass = currentClass;
        this.students = studentService.getAllStudentsForClass(currentClass);

        // 初始化组件
        System.out.println("this.students: " + this.students);
        selectButton = new JButton("随机挑选一位学生");
        resultLabel = new JLabel("结果");

        setLayout();

        // 添加按钮点击事件
        selectButton.addActionListener(e -> {
            String studentName;

            if (!students.isEmpty()) {
                studentName = getRandomStudent(students);
                System.out.println("student: " + studentName);
                resultLabel.setText("随机挑选的学生: " + studentName);
            } else {
                resultLabel.setText("该班级没有学生");
            }

        });
    }

    private void setLayout() {
        // 设置面板布局
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 1)); // 2行1列
        panel.add(selectButton);
        panel.add(resultLabel);
        
        // 创建对话框
        dialog = new JDialog();
        dialog.setTitle("随机学生选择器");
        dialog.setContentPane(panel);
        dialog.setSize(300, 150);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setLocationRelativeTo(null);
    }

    private String getRandomStudent(List<String> studentList) {
        Random random = new Random();

        return studentList.get(random.nextInt(studentList.size()));
    }

    public void setVisible(boolean visible) {
        dialog.setVisible(visible);
    }
}
